package com.gaoyi.basemodule.basedialog;


import android.view.KeyEvent;

import androidx.fragment.app.FragmentActivity;

import com.gaoyi.basemodule.R;


public class LoadingDialogUtils {
    private static volatile LoadingDialogUtils instance;

    private LoadingDialogUtils() {
    }

    public static LoadingDialogUtils getInstance() {
        if (instance == null) {
            synchronized (LoadingDialogUtils.class) {
                if (instance == null) {
                    instance = new LoadingDialogUtils();
                }
            }
        }
        return instance;
    }

    private ToastDialog dialog;

    public void showLoading(FragmentActivity mContext, String msg) {
        dismiss();
        dialog = new ToastDialog(mContext).setMessage(msg).setIco(R.drawable.ic_loading);
        dialog.setCancelable(true);
        dialog.show(mContext.getSupportFragmentManager());
    }

    public void showLoading(FragmentActivity mContext, OnBackListener onBackListener) {
        dismiss();
        showLoading(mContext, mContext.getString(R.string.loading), onBackListener);
    }

    public void showLoading(FragmentActivity mContext, String msg, OnBackListener onBackListener) {
        dismiss();
        dialog = new ToastDialog(mContext, (dialogInterface, i, keyEvent) -> {
            if (i == KeyEvent.KEYCODE_BACK) {
                onBackListener.onBackListener();
            }
            return false;
        }).setMessage(msg).setIco(R.drawable.ic_loading);
        dialog.setCancelable(true);
        try {
            dialog.show(mContext.getSupportFragmentManager());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnBackListener {
        void onBackListener();
    }

    public void showLoading(FragmentActivity mContext) {
        showLoading(mContext, mContext.getString(R.string.loading));
    }

    public void dismiss() {
        try {
            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
